package com.xiaoyu.lingdian.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.xiaoyu.lingdian.core.mybatis.page.Page;
import com.xiaoyu.lingdian.entity.CoreAccount;
import com.xiaoyu.lingdian.entity.CoreFunction;
import com.xiaoyu.lingdian.entity.CoreRole;
import com.xiaoyu.lingdian.entity.CoreUser;
import com.xiaoyu.lingdian.entity.weixin.Constant;
import com.xiaoyu.lingdian.entity.weixin.WxTemplate;
import com.xiaoyu.lingdian.entity.weixin.TemplateData;
import com.xiaoyu.lingdian.service.CoreAccountService;
import com.xiaoyu.lingdian.service.CoreFunctionService;
import com.xiaoyu.lingdian.service.CoreRoleService;
import com.xiaoyu.lingdian.service.CoreUserService;
import com.xiaoyu.lingdian.tool.encrypt.MD5Util;
import com.xiaoyu.lingdian.tool.init.ConfigIni;
import com.xiaoyu.lingdian.tool.StringUtil;
import com.xiaoyu.lingdian.tool.out.ResultMessageBuilder;
import com.xiaoyu.lingdian.tool.wx.GetExistAccessToken;
import com.xiaoyu.lingdian.tool.wx.WeixinUtil;
import com.xiaoyu.lingdian.vo.CoreAccountVO;

@Controller
@RequestMapping(value = "/admin")
public class AdminController extends BaseController {

	/**
	 * 用户表
	 */
	@Autowired
	private CoreAccountService coreAccountService;
	
	/**
	 * 角色表
	 */
	@Autowired
	private CoreRoleService coreRoleService;
	
	/**
	 * 功能菜单表
	 */
	@Autowired
	private CoreFunctionService coreFunctionService;

	/**
	 * 用户表
	 */
	@Autowired
	private CoreUserService coreUserService;
	
	/**
	 * 登录
	 * 
	 * @param USERCODE  工号或用户名
	 * @param PWD 密码
	 * @param response
	 */
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public void login(String USERCODE, String PWD, HttpServletResponse response) {
		logger.info("login start");
		if (StringUtil.isEmpty(USERCODE)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "[USERCODE]不能为空!"), response);
			return;
		}
		if (StringUtil.isEmpty(PWD)) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "[PWD]不能为空!"), response);
			return;
		}
		CoreAccount coreAccount = new CoreAccount();
		coreAccount.setCractName(USERCODE);
		CoreAccount account = coreAccountService.getCoreAccount(coreAccount);
		String md5PWD=MD5Util.getMD5(PWD);
		if (account == null || !(md5PWD).equals(account.getCractPassword())) {
			writeAjaxJSONResponse(ResultMessageBuilder.build(false, -1, "用户或密码错误！"), response);
			logger.info("login end");
			return;
		}
		CoreAccountVO coreAccountVO = new CoreAccountVO();
		coreAccountVO.convertPOToVO(account);
		List<CoreFunction> functionList=new ArrayList<CoreFunction>();
		// 返回菜单
		if (account.getCractRoles() != null) {
			String[] roles = account.getCractRoles().split("\\|");
			CoreRole coreRole;
			CoreFunction coreFunction;
			for (int i = 0; i < roles.length; i++) { // 获取角色
				// 根据角色查询功能菜单
				coreRole = new CoreRole();
				coreRole.setCrrolUuid((roles[i]));
				CoreRole role = coreRoleService.getCoreRole(coreRole);
				if (role != null && role.getCrrolFuns() != null) {
					String[] menus = role.getCrrolFuns().split("\\|");
					for (int y = 0; y < menus.length; y++) { // 获取权限
						coreFunction = new CoreFunction();
						coreFunction.setCrfntUuid(menus[y]);
						coreFunction.setCrfntStatus(1);
						CoreFunction function = coreFunctionService.getCoreFunction(coreFunction);
						if (function != null) {
							functionList.add(function);
						}
					}
				}
			}
		}
		coreAccountVO.setCoreFunctions(functionList);
		
		writeAjaxJSONResponse(ResultMessageBuilder.build(true, 1, "登录成功!", coreAccountVO), response);
		logger.info("login end");
	}
	
	/**
	 * 发布公告
	 * 
	 * @param response
	 */
	@RequestMapping(value = "/send/notice", method = RequestMethod.POST)
	public void sendNotice(String modelId, String first, String service, String detail, String time, String location, 
			String reason, String remark, HttpServletResponse response) {
		logger.info("sendNotice start");
		GetExistAccessToken getExistAccessToken= GetExistAccessToken.getInstance();
		Page<CoreUser> page = coreUserService.findCoreUserByCnd(null, null, 1, 5000);
		for (CoreUser coreUser : page.getResult()) {
			if (null != coreUser.getCrusrOpenid()) {
				WxTemplate t = new WxTemplate();
				t.setUrl("");
				t.setTouser(coreUser.getCrusrOpenid());
				t.setTopcolor("#000000");
				t.setTemplate_id(modelId);
				Map<String,TemplateData> m = new HashMap<String,TemplateData>();
				
				TemplateData firstData = new TemplateData();
				firstData.setColor("#000000");
				firstData.setValue(first);
				m.put("first", firstData);
				
				TemplateData serviceData = new TemplateData();
				serviceData.setColor("#000000");
				serviceData.setValue(service);
				m.put("service", serviceData);
				
				TemplateData detailData = new TemplateData();
				detailData.setColor("#000000");
				detailData.setValue(detail);
				m.put("detail", detailData);
				
				TemplateData timeData = new TemplateData();
				timeData.setColor("#000000");
				timeData.setValue(time);
				m.put("time", timeData);
				
				TemplateData locationData = new TemplateData();
				locationData.setColor("#000000");
				locationData.setValue(location);
				m.put("location", locationData);
				
				TemplateData reasonData = new TemplateData();
				reasonData.setColor("#000000");
				reasonData.setValue(reason);
				m.put("reason", reasonData);
				
				TemplateData remarkData = new TemplateData();
				remarkData.setColor("#000000");
				remarkData.setValue(remark);
				m.put("remark", remarkData);
				
				t.setData(m);
				String jsonStr = JSONObject.fromObject(t).toString(); //此处你应该代入自己的template
				String appid = ConfigIni.getIniStrValue("WEIXIN_CONFIG", "appid", Constant.APP_ID);
				String appsecret = ConfigIni.getIniStrValue("WEIXIN_CONFIG", "appsecret", Constant.APP_SECRET);
				String accessToken = getExistAccessToken.getExistAccessToken(appid, appsecret, "accessToken");
				WeixinUtil.sendTemplateMsg(jsonStr, accessToken);
			}
		}

		writeAjaxJSONResponse(ResultMessageBuilder.build(true, 1, "公告发布成功!"), response);
		logger.info("sendNotice end");
	}

}